<?php

class UploadController extends BaseAdminController {

    public $menu = array(
        array('label' => 'New upload', 'url' => array('upload/create')),
        array('label' => 'List images', 'url' => array('upload/index'))
    );

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('index', 'create'),
                'users' => array('admin'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $this->redirect(array('create'));
    }

    private function initYear() {
        $years = array();
        for ($i = 2013; $i < 2020; $i++) {
            $item = array('id' => $i, 'name' => $i);
            $years[] = $item;
        }
        return $years;
    }

    private function initMonth() {
        $months = array();
        for ($i = 1; $i < 13; $i++) {
            $item = array('id' => $i, 'name' => $i);
            $months[] = $item;
        }
        return $months;
    }

    /**
     * Lists all models.
     */
    public function actionCreate() {
        $months = $this->initMonth();
        $years = $this->initYear();
        $imagesUpload = new Images;
        $message = '';
        if (isset($_POST['Images'])) {
            $imagesUpload->attributes = $_POST['Images'];

            //get images and check
            $canSave = true;
            $images = CUploadedFile::getInstancesByName('url');
            if (isset($images) && count($images) > 0) {
                foreach ($images as $image => $pic) {
                    $imageName = $this->renameImage($pic->name, $imagesUpload->month, $imagesUpload->year);
                    if (strlen('contents/uploads/images/' . $imagesUpload->year . '/' . $imagesUpload->month . '/' . $imageName) > 255) {//check length of images name
                        $message = '"' . $imageName . '":' . Yii::t('article', 'longImageName');
                        $canSave = false;
                        break;
                    }
                }
            }
            //save to database
            if ($canSave) {
                //begin upload images
                $imagesName = array();
                foreach ($images as $image => $pic) {
                    $imageName = $this->renameImage($pic->name, $imagesUpload->month,$imagesUpload->year);
                    $path = Yii::getPathOfAlias('webroot.contents.uploads.images.' . $imagesUpload->year . '.' . $imagesUpload->month) . DIRECTORY_SEPARATOR . $imageName;
                    if ($pic->saveAs($path)) {
                        $imagesName[] = $imageName;
                    }
                }
                //save model
                foreach ($imagesName as $imageName) {
                    $imageNew = new Images;
                    $imageNew->month = $imagesUpload->month;
                    $imageNew->year = $imagesUpload->year;
                    $imageNew->url = 'contents/uploads/images/' . $imagesUpload->year . '/' . $imagesUpload->month . '/' . $imageName;
                    $saved = $imageNew->save();
                    if (!$saved) {//if saving fail, delete uploaded images
                        $path = Yii::getPathOfAlias('webroot.contents.uploads.images.' . $imagesUpload->year . '.' . $imagesUpload->month) . DIRECTORY_SEPARATOR . $imageName;
                        unlink($path);
                    }
                }
                Yii::app()->user->setFlash('message', Yii::t('article', 'successUpdate'));
                $this->redirect(array('index'));
            }
        }
        $this->render('create', array(
            'months' => $months,
            'years' => $years,
            'message' => $message,
            'imagesUpload' => $imagesUpload
        ));
    }

    public function renameImage($imageName, $month, $year) {
        $newName = str_replace(array(' ', '\\', '/', ',', '(', ')', '-', '"', '\'', '%'), '_', $imageName);
        $newName = $month.$year.'_' . $newName;
        //$newName = time() . '_' . $newName;
        return $newName;
    }

    /**
     * action Images
     */
    public function actionImages($id) {
        $product = Product::model()->findByPk($id);
        $productImages = $product->productImages;
        Yii::app()->clientScript->scriptMap['jquery.js'] = false;
        $this->renderPartial('showImages', array('productImages' => $productImages,), false, true);
    }

    /**
     * delete image update
     */
    public function actionDeleteImage($id) {
        $productImage = ProductImage::model()->findByPk($id);
        $productImage->delete();
        // die;
    }

}
